#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>

class InetAddr
{
private:
    //端口号网络转主机
    void PortNet2Host()
    {
        _prot = ::ntohs(_addr.sin_port);
    }

    //ip网络转主机
    void IpNet2Host()
    {
        char ipbuffer[64];
        const char *ip = ::inet_ntop(AF_INET, &_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        (void)ip;
    }

public:
    InetAddr() = default;

    //ip到时默认使用INADDR_ANY
    InetAddr(uint16_t prot)
        : _prot(prot),
          _ip("")
    {
        _addr.sin_family = AF_INET; //设置地址族
        _addr.sin_port = ::htons(_prot);    //设置端口号
        _addr.sin_addr.s_addr = INADDR_ANY; //设置为INADDR_ANY
    }

    //拷贝构造
    InetAddr(const struct sockaddr_in &addr) : _addr(addr)
    {
        //将网络转主机
        PortNet2Host();
        IpNet2Host();
    }

    //长度
    socklen_t Addr_size()
    {
        return sizeof(_addr);
    }

    //端口号
    uint16_t GetProt()
    {
        return _prot;
    }

    //ip
    std::string GetIp()
    {
        return _ip;
    }

    //返回struct sockaddr *
    struct sockaddr * GetAddr()
    {
        return (struct sockaddr *) &_addr;
    }

    ~InetAddr() = default;

private:
    uint16_t _prot;
    std::string _ip;
    struct sockaddr_in _addr;
};